package codec

import (
	"bytes"

	"github.com/gogf/gf/v2/container/garray"
	"github.com/panjf2000/gnet/v2"
	"github.com/wzh200x/gateServer/network/message"
	"github.com/wzh200x/gateServer/network/reader"
	"github.com/wzh200x/hyperNexus/hyperNexusType"
)

type Codec struct {
	ConnectId    hyperNexusType.TypeConnectId // 连接ID
	Buf          bytes.Buffer                 // 从实际socket中读取到的数据缓存
	PacketReader *reader.PacketReader         // 包读取
}

func NewCodec(conId hyperNexusType.TypeConnectId) *Codec {
	return &Codec{
		ConnectId:    conId,
		PacketReader: reader.NewPacketReader(),
	}
}

func (this *Codec) ReadBufferBytes(c gnet.Conn) gnet.Action {
	size := c.InboundBuffered()
	buf := make([]byte, size)
	read, err := c.Read(buf)
	if err != nil {
		return gnet.Close
	}
	if read < size {
		return gnet.Close
	}
	this.Buf.Write(buf)
	return gnet.None
}

func (this *Codec) Decode() (*garray.Array, error) {
	packets := garray.New()
	for {
		if this.PacketReader.ReadSize >= this.Buf.Len() {
			break
		}
		transformBuf := this.Buf.Bytes()[this.PacketReader.ReadSize:]
		if len(transformBuf) >= message.HeaderSize {
			err, packet := this.PacketReader.Reader(transformBuf)
			if err != nil {
				this.Buf.Reset()
				this.PacketReader.Reset()
				return nil, err
			}
			if packet != nil {
				packets.Append(packet)
			}
		}

	}
	this.Buf.Reset()
	this.PacketReader.Reset()
	return packets, nil
}
